<template>
  <div ref="applicationCenterRef">
    <div class="shadow-[0_3px_10px_0_rgba(0,0,0,0.05)]">
      <div class="max-w-1230 my-0 mx-auto p-15 flex justify-between items-center">
        <div class="flex items-center">
          <a href="http://www.ckjr001.com" target="blank">
            <img src="@/assets/logo/logo-icon.png" width="180" alt="" srcset="" />
          </a>
        </div>
        <div class="flex items-center">
          <span
            v-if="!isMobile"
            class="pl-18 ml-20 text-14 text-accent-color mr-20 cursor-pointer"
            @click="linkToHelp"
          >
            {{ $t("route.documentCenter") }}
          </span>
          <el-dropdown class="cursor-pointer" @command="handleClick">
            <div class="flex items-center">
              <span class="mr-10 text-14 text-333333">{{ username }}</span>
              <el-icon class="text-14 text-666666"><CaretBottom /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="accountFrom == 'open'" :command="'modifyPsw'">
                  修改密码
                </el-dropdown-item>
                <el-dropdown-item :command="'logout'">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>
    <div class="max-w-1230 my-0 mx-auto py-24 px-15">
      <div class="flex gap-20 mb-36 items-center">
        <el-button type="primary" :disabled="createCount >= 5" @click="openCreateDialog">
          创建应用
        </el-button>
        <div class="text-14 text-666666">
          每个账号最多可创建5个应用，应用只有审核通过后才能调用访控制台
        </div>
      </div>
      <div class="relative">
        <div v-if="appList && appList.length" class="flex gap-20 flex-wrap">
          <!-- status 状态：-1不通过  0审核中  1已通过 -->
          <div
            v-for="item in appList"
            class="bg-f8f9fb p-20 w-376 h-177 rounded-8 relative box-border cursor-pointer"
            @click="linkToApplicationInfo(item)"
          >
            <div class="flex flex-col gap-5 text-12 text-999999">
              <div class="text-16 text-333333 font-bold w-225 truncate">
                {{ item.appName }}
              </div>
              <div>创建者：{{ item.createUsername }}</div>
              <div>创建时间：{{ item.createdAt }}</div>
              <div>授权店铺：{{ item.companyName }}</div>
              <el-button
                v-if="item.roleType == 1"
                class="mt-8 w-79 pt-7"
                plain
                style="height: 28px !important"
                size="small"
                @click.stop="confirmLogOff(item)"
              >
                注销
              </el-button>
            </div>
            <i
              class="iconfont text-60 absolute right-10 top-0 w-60 h-60"
              :class="{
                'text-accent-color icon-yitongguo': item.status == 1,
                'text-red-600 icon-weitongguo': item.status == -1,
                'text-cccccc icon-verify-active': item.status == 0,
              }"
            />
          </div>
        </div>
        <div v-else class="absolute bg-white h-480 w-full pt-0 pl-0 flex flex-col items-center">
          <img src="../../assets/images/empty.png" class="w-166 h-92" alt="" />
          <div class="text-14 mt-30 text-999999">暂无数据</div>
        </div>
      </div>
    </div>
    <SuperDialog
      :model-value="isShowDialog"
      title="创建应用"
      width="500px"
      @confirm="handleConfirm"
      @cancel="handleClose"
    >
      <el-form
        ref="appFormRef"
        :model="appForm"
        :rules="appFormRules"
        label-width="auto"
        status-icon
      >
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="appForm.appName" />
        </el-form-item>
        <el-form-item label="授权店铺" prop="companyId">
          <template v-if="relateShopList.length > 0">
            <el-radio-group v-model="appForm.companyId">
              <el-radio
                v-for="item in relateShopList"
                :key="item.companyId"
                :value="item.companyId"
                :disabled="checkExpireTime(item.expireTime)"
              >
                {{ item.companyName
                }}{{ checkExpireTime(item.expireTime) ? "（店铺已过期，不可绑）" : "" }}
              </el-radio>
            </el-radio-group>
          </template>
          <span v-else class="text-cccccc">暂无可绑定店铺</span>
        </el-form-item>
      </el-form>
    </SuperDialog>
  </div>
</template>
<script setup lang="ts">
import router from "@/router";
import { useAppStore, useUserStore, useUserStoreHook } from "@/store";
import SuperDialog from "@/views/templatePage/SuperDialog/index.vue";
import AuthAPI, { type AppListInfo, RelateShopInfo } from "@/api/auth";
import { Action, FormInstance, FormRules } from "element-plus";
import { DeviceEnum } from "@/enums/DeviceEnum";
import { setHasOperatePermission } from "@/utils/auth";
const appStore = useAppStore();
const isMobile = computed(() => appStore.device === DeviceEnum.MOBILE);
// 用户状态管理器
const userStore = useUserStore();
const loginResult = userStore.loginResult;
// 用户名
const username = ref<string>(loginResult.username);
// 账号类型: shop (来自商家) open (来自开放平台)
const accountFrom = ref<string>(loginResult.from);
// 跳转至帮助中心
const linkToHelp = () => {
  window.open("https://apifox.com/apidoc/shared-76452342-3d25-4e64-8017-8c7ec86c728f");
};
// 操作类型
const handleClick = (type: string) => {
  if (type == "modifyPsw") {
    linkToModify();
  } else if (type == "logout") {
    useUserStoreHook()
      .logout()
      .then(() => {
        location.reload();
        router.push("/login");
      });
  }
};
// 修改密码
const linkToModify = () => {
  router.push("/modifyPassword");
};

// 平台列表信息
const appList = ref<AppListInfo[]>([]);
// 已创建应用数量
const createCount = ref<number>(0);
// 防止多次加载
const btnLoading = ref<boolean>(false);
// 是否展示弹出框
const isShowDialog = ref<boolean>(false);
// 表单Ref
const appFormRef = ref<FormInstance>();
// 表单类型
interface AppForm {
  appName: string;
  companyId: string;
}
// 表单数据
const appForm = ref<AppForm>({
  // 应用名称
  appName: "",
  // 授权店铺
  companyId: "",
});
// 表单规则
const appFormRules = ref<FormRules<AppForm>>({
  appName: [
    {
      required: true,
      message: "请填写应用名称",
      trigger: "blur",
    },
  ],
  companyId: [
    {
      required: true,
      message: "请选择授权店铺",
      trigger: "change",
    },
  ],
});
// 关联平台列表
const relateShopList = ref<RelateShopInfo[]>([]);
// 获取平台列表
const getAppList = () => {
  AuthAPI.getAppList({ username: username.value }).then((data) => {
    appList.value = data.appList;
    createCount.value = data.createCount;
  });
};
// 检查店铺是否过期
const checkExpireTime = (expireTime: string) => {
  const curExpireTime = expireTime ? new Date(expireTime).getTime() : 0;
  return curExpireTime <= new Date().getTime();
};
// 初始化表单数据
const initializeForm = () => {
  appForm.value = {
    // 应用名称
    appName: "",
    // 授权店铺
    companyId: "",
  };
  // 重置表单并清除校验状态
  appFormRef.value?.resetFields();
};
// 创建应用提示弹出框
const openCreateDialog = () => {
  ElMessageBox.alert("开放平台为付费模块，请先联系服务经理咨询费用，确认付费后再创建应用", "提示", {
    confirmButtonText: "知道了",
    callback: (action: Action) => {
      if (action === "cancel") return;
      initializeForm();
      getRelateShop();
    },
  });
};
// 关闭创建应用弹出框
const handleClose = () => {
  isShowDialog.value = false;
};
// 关联平台
const getRelateShop = () => {
  AuthAPI.getRelateShop({ username: username.value }).then((data) => {
    relateShopList.value = data.shopList;
    isShowDialog.value = true;
  });
};
// 创建应用
const handleConfirm = (row: AppListInfo) => {
  // 验证表单参数是否正确
  appFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      AuthAPI.createApp({ ...appForm.value, username: username.value }).then((data) => {
        isShowDialog.value = false;
        ElMessage.success("创建应用成功，等待审核！");
        getAppList();
      });
    }
  });
};
// applicationCenter页面元素用于解决vite刷新后不跳转问题，只有这个页面存在
const applicationCenterRef = ref(null);
// 进入应用
const linkToApplicationInfo = (row: AppListInfo) => {
  if (row.status !== 1) {
    ElMessage.warning(`应用${row.status == -1 ? "审核未通过" : "审核中"}，暂不支持进入应用`);
    return;
  }
  if (btnLoading.value) return;
  btnLoading.value = true;
  userStore
    .selectApp({ oPid: row.oPid, username: username.value })
    .then(async () => {
      setHasOperatePermission(row.roleType);
      btnLoading.value = false;
      await userStore.getUserInfo();
      await router.push("/");
      setTimeout(() => {
        if (applicationCenterRef.value) {
          location.reload();
        }
      }, 100);
    })
    .catch(() => {
      btnLoading.value = false;
    });
};
// 注销应用
const confirmLogOff = (row: AppListInfo) => {
  ElMessageBox.alert("确认要注销该应用吗？", "注销确认", {
    showCancelButton: true,
    cancelButtonText: "取消",
    confirmButtonText: "确定",
    callback: (action: Action) => {
      if (action === "cancel") return;
      AuthAPI.deleteApp({ oPid: row.oPid, username: username.value }).then((data) => {
        ElMessage.success("应用注销成功!");
        getAppList();
      });
    },
  });
};

onMounted(() => {
  getAppList();
});
</script>

<style scoped lang="scss"></style>
